package controllers

import (
	"beday20/cache"
	"beday20/models"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}

type Res struct {
	Code    int         `json:"code"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "账号密码不能为空",
		}
		c.ServeJSON()
		return
	}

	var user models.User

	if err := models.DB.Find(&user).Error; err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "系统错误",
		}
		c.ServeJSON()
		return
	}

	key := "user_error_" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if count >= "3" {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "密码错误次数过多",
		}
		c.ServeJSON()
		return
	}

	if user.Password != password {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == "2" {
			cache.Rdb.Expire(cache.Ctx, key, time.Minute*10)
		}
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code:    200,
		Data:    user,
		Message: "登录成功",
	}
	c.ServeJSON()
	return
}
